package logic

import (
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/prices"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/utils"
)

// ------------- 逻辑层logic - 设备相关 ------------------//

type DeviceLogic struct {
}

func NewDeviceLogic() *DeviceLogic {
	return &DeviceLogic{}
}

// GetDeviceInfoByDeviceSn 获取设备详情
func (l *DeviceLogic) GetDeviceInfoByDeviceSn(sn string) *devices.DeviceWithPlace {
	devInfo := dao.NewDeviceDao().GetDeviceInfoWithPlace(sn).Unwrap().(*devices.DeviceWithPlace)
	if devInfo.FeeMode == 1 { // 计时
		devInfo.RuleInfo = dao.NewPricesDao().
			WxGetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 1, 1, int(devInfo.FeeMode), "create_at desc").Unwrap().([]prices.PriceModel)
	}
	if devInfo.FeeMode == 2 { // 套餐 就显示4种 20分钟的不显示
		devInfo.RuleInfo = dao.NewPricesDao().
			WxGetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 4, 0, int(devInfo.FeeMode), "create_at desc, priority asc").Unwrap().([]prices.PriceModel)

	}
	return devInfo
}

// GetDeviceInfoByDeviceSn 微信端2.0版本获取设备信息
func (l *DeviceLogic) WXGetDeviceInfoByDeviceSn(sn string) *devices.DeviceWithPlace {
	devInfo := dao.NewDeviceDao().GetDeviceInfoWithPlace(sn).Unwrap().(*devices.DeviceWithPlace)
	if devInfo.FeeMode == 1 { // 计时
		devInfo.RuleInfo = dao.NewPricesDao().
			WxGetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 1, 1, int(devInfo.FeeMode), "create_at desc").Unwrap().([]prices.PriceModel)
	}
	if devInfo.FeeMode == 2 { // 套餐 就显示4种 20分钟的不显示
		devInfo.RuleInfo = dao.NewPricesDao().
			WxGetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 4, 0, int(devInfo.FeeMode), "create_at desc, priority asc").Unwrap().([]prices.PriceModel)
	}
	return devInfo
}

// HandleLogicGetPassword 获取密码业务逻辑
func (l *DeviceLogic) HandleLogicGetPassword(param *request.GetPasswordReq) (password string, useTime int64) {
	//p,idx,t := l.HandleGetPassword(data) // 密码、密码序号、使用时长
	//if data.IsYc == 1 { // 易充
	//	if idx >= 40 {
	//		idx = 1
	//	}
	//} else {
	//	if idx >= 20 {
	//		idx = 1
	//	}
	//
	//}
	//dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, data.DeviceSn, idx)
	//return p, int64(t)
	if param.ProductId == "" {
		orderInfo := dao.NewOrderDao().GetOrderInfoByOpenidAndSn(param.Openid, param.DeviceSn).Unwrap().(*orders.OrderModel)
		param.ProductId = orderInfo.ProductId
	}

	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)

	if devInfo.FeeMode == 1 { // 计时模式
		useTime = int64(ruleInfo.MaxTime) // 单套餐
	} else { // 套餐模式
		useTime = int64(ruleInfo.UseDuration)
	}
	pwdTime := useTime
	useTime = useTime * 60
	var pwd string
	var idx int
	// 4键
	if devInfo.PwdSecretKey == "RUIOO10" {
		pwd, idx = helper.GetYCPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 40 {
			idx = 1
		}
	} else if devInfo.PwdDecodeType == "ZM_PD" {
		pwd, idx = helper.GetPdPassword(param.DeviceSn, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 25 {
			idx = 1
		}
	} else if devInfo.PwdDecodeType == "XM_PD" {
		pwd, idx = helper.GetXmPdPassword(param.DeviceSn, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 49 {
			idx = 1
		}
	} else {
		pwd, idx = helper.GetPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 20 {
			idx = 1
		}
	}
	dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, param.DeviceSn, idx)
	return pwd, useTime
}

// HandleGetPassword 获取密码、密码序号、使用时长
//func (l *DeviceLogic) HandleGetPassword(param *request.GetPasswordReq) (pwd string, idx int, useTime int) {
//	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
//	ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)
//
//	if devInfo.FeeMode == 1 { // 计时模式
//		useTime = ruleInfo.MaxTime  // 单套餐
//	} else { // 套餐模式
//		useTime = ruleInfo.UseDuration
//	}
//	pwdTime := useTime
//	useTime = useTime * 60
//	if param.IsYc == 1 { // 易充4键 6密
//		pwd,idx = helper.GetYCPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), pwdTime)
//	} else { // 天海5键 5密
//		pwd,idx = helper.GetPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), pwdTime)
//	}
//
//	return
//}

// handleUpdateDevicePwdIndex 更新密码序号
func (l *DeviceLogic) handleUpdateDevicePwdIndex(params ...interface{}) {
	dao.NewDeviceDao().UpdateDevicePwdNo(params[0].(string), params[1].(int))
}

// HandleLogicResetPassword 重置密码
//func (l *DeviceLogic) HandleLogicResetPassword(data *request.GetPasswordReq) (pwd string, count int64) {
//	p,idx,_ := l.HandleGetPassword(data)
//	keyOrderPwdCount := utils.Join(data.TradeNo, "-pwdcount")
//	// 计数
//	c,_ := global.Rdb.Incr(context.Background(), keyOrderPwdCount).Result()
//	log.Println(c)
//	// 更新设备密码序号
//	dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, data.DeviceSn, idx)
//	//if c > 10 {
//	//	c = 0
//	//}
//	if data.IsYc == 1 { // 易充
//		if c > 40 {
//			global.Rdb.DecrBy(context.Background(), keyOrderPwdCount, 40) //重新计数
//		}
//	} else {
//		if c > 20 {
//			global.Rdb.DecrBy(context.Background(), keyOrderPwdCount, 20) //重新计数
//		}
//	}
//
//	return p, c
//}

func (l *DeviceLogic) HandleUseTime(param *request.GetPasswordReq) (beginTime string, t int) {
	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)
	orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	var totalTime int
	if devInfo.FeeMode == 1 { // 计时模式
		totalTime = ruleInfo.MaxTime
	} else {
		totalTime = ruleInfo.UseDuration
	}

	totalTime = totalTime * 60 //总使用时长 秒
	//log.Println("totalTime", totalTime)
	// 已使用时长 当前时间 - 订单支付时间
	//useTime := int(time.Now().Unix() - int64(orderInfo.PayAt))
	// 已使用时长 当前时间 - 订单开始时长
	useTime := int(time.Now().Unix() - int64(orderInfo.BeginAt))
	//log.Println(time.Now().Unix())
	//log.Println(int64(orderInfo.PayAt))
	//log.Println("useTime", useTime)
	if useTime <= totalTime {
		t := totalTime - useTime
		h, m, s := utils.ResolveTime(t)
		//log.Println(h,m,s)
		var hour, minute, second string
		if h <= 9 {
			hour = utils.Join("0", strconv.Itoa(h))
		} else {
			hour = strconv.Itoa(h)
		}
		if m <= 9 {
			minute = utils.Join("0", strconv.Itoa(m))
		} else {
			minute = strconv.Itoa(m)
		}
		if s <= 9 {
			second = utils.Join("0", strconv.Itoa(s))
		} else {
			second = strconv.Itoa(s)
		}
		//log.Println(hour,minute,second)
		beginTime = utils.Join(hour, ":", minute, ":", second)
	} else {
		beginTime = "00:00:00"
	}

	// 剩余使用时长 总时长-已使用时长

	//log.Println("beginTime", beginTime)
	return beginTime, useTime
}

func (l *DeviceLogic) HandleAliPayUseTime(param *request.GetPasswordReq) (beginTime string, t int) {
	//devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	//ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)
	orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	//var totalTime int
	//if devInfo.FeeMode == 1 { // 计时模式
	//	totalTime = ruleInfo.MaxTime
	//} else {
	//	totalTime = ruleInfo.UseDuration
	//}

	//totalTime = totalTime * 60 //总使用时长 秒
	//log.Println("totalTime", totalTime)
	// 已使用时长 当前时间 - 订单支付时间
	//useTime := int(time.Now().Unix() - int64(orderInfo.PayAt))
	// 已使用时长 当前时间 - 订单开始时长
	useTime := int(time.Now().Unix() - int64(orderInfo.BeginAt))
	//log.Println(time.Now().Unix())
	//log.Println(int64(orderInfo.PayAt))
	//log.Println("useTime", useTime)
	//if useTime <= totalTime {
	//	t := totalTime - useTime
	//	h, m, s := utils.ResolveTime(t)
	//	//log.Println(h,m,s)
	//	var hour, minute, second string
	//	if h <= 9 {
	//		hour = utils.Join("0", strconv.Itoa(h))
	//	} else {
	//		hour = strconv.Itoa(h)
	//	}
	//	if m <= 9 {
	//		minute = utils.Join("0", strconv.Itoa(m))
	//	} else {
	//		minute = strconv.Itoa(m)
	//	}
	//	if s <= 9 {
	//		second = utils.Join("0", strconv.Itoa(s))
	//	} else {
	//		second = strconv.Itoa(s)
	//	}
	//	//log.Println(hour,minute,second)
	//	beginTime = utils.Join(hour, ":", minute, ":", second)
	//} else {
	//	beginTime = "00:00:00"
	//}

	// 剩余使用时长 总时长-已使用时长

	//log.Println("beginTime", beginTime)
	return beginTime, useTime
}

// HandleGetAutomatePasswordReplenish 售货机补货查询密码
func (l *DeviceLogic) HandleGetAutomatePasswordReplenish(deviceSn string, useTime int64) (password string) {
	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(deviceSn).Unwrap().(*devices.DeviceType)

	pwdTime := useTime
	useTime = useTime * 60
	var pwd string
	var idx int
	if devInfo.PwdDecodeType == "ZM_PD" {
		pwd, idx = helper.GetPdPassword(deviceSn, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 25 {
			idx = 1
		}
	}
	if pwd != "" {
		dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, deviceSn, idx)
	}
	return pwd
}

// 公众号优惠领取
func (l *DeviceLogic) HandleGetPasswordWxCoupon(deviceSn string, useTime int64) (password string) {
	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(deviceSn).Unwrap().(*devices.DeviceType)

	pwdTime := useTime
	useTime = useTime * 60
	var pwd string
	var idx int
	// 4键
	if devInfo.PwdSecretKey == "RUIOO10" {
		pwd, idx = helper.GetYCPassword(deviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 40 {
			idx = 1
		}
	} else if devInfo.PwdDecodeType == "ZM_PD" {
		pwd, idx = helper.GetPdPassword(deviceSn, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 25 {
			idx = 1
		}
	} else {
		pwd, idx = helper.GetPassword(deviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 20 {
			idx = 1
		}
	}
	dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, deviceSn, idx)
	return pwd
}

//------------支付宝小程序操作

func (l *DeviceLogic) HandleLogicGetPasswordZfb(param *request.GetZfbPasswordReq) (password string, useTime int64) {
	//p,idx,t := l.HandleGetPassword(data) // 密码、密码序号、使用时长
	//if data.IsYc == 1 { // 易充
	//	if idx >= 40 {
	//		idx = 1
	//	}
	//} else {
	//	if idx >= 20 {
	//		idx = 1
	//	}
	//
	//}
	//dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, data.DeviceSn, idx)
	//return p, int64(t)

	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)

	if devInfo.FeeMode == 1 { // 计时模式
		useTime = int64(ruleInfo.MaxTime) // 单套餐
	} else { // 套餐模式
		useTime = int64(ruleInfo.UseDuration)
	}
	pwdTime := useTime
	useTime = useTime * 60
	var pwd string
	var idx int
	// 4键
	if devInfo.PwdSecretKey == "RUIOO10" {
		pwd, idx = helper.GetYCPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 40 {
			idx = 1
		}
	} else {
		pwd, idx = helper.GetPassword(param.DeviceSn, devInfo.PwdSecretKey, int(devInfo.PwdIndex), int(pwdTime))
		if idx >= 20 {
			idx = 1
		}
	}
	dingo.Task(l.handleUpdateDevicePwdIndex, func() {}, param.DeviceSn, idx)
	return pwd, useTime
}

func (l *DeviceLogic) HandleAliPayUseTimeZfb(param *request.GetZfbPasswordReq) (beginTime string, t int) {
	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	ruleInfo := dao.NewPricesDao().GetPriceDetail(param.ProductId).Unwrap().(*prices.PriceModel)
	orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	var totalTime int
	if devInfo.FeeMode == 1 { // 计时模式
		totalTime = ruleInfo.MaxTime
	} else {
		totalTime = ruleInfo.UseDuration
	}

	totalTime = totalTime * 60 //总使用时长 秒
	//log.Println("totalTime", totalTime)
	// 已使用时长 当前时间 - 订单支付时间
	//useTime := int(time.Now().Unix() - int64(orderInfo.PayAt))
	// 已使用时长 当前时间 - 订单开始时长
	useTime := int(time.Now().Unix() - int64(orderInfo.BeginAt))
	//log.Println(time.Now().Unix())
	//log.Println(int64(orderInfo.PayAt))
	//log.Println("useTime", useTime)
	//if useTime <= totalTime {
	//	t := totalTime - useTime
	//	h, m, s := utils.ResolveTime(t)
	//	//log.Println(h,m,s)
	//	var hour, minute, second string
	//	if h <= 9 {
	//		hour = utils.Join("0", strconv.Itoa(h))
	//	} else {
	//		hour = strconv.Itoa(h)
	//	}
	//	if m <= 9 {
	//		minute = utils.Join("0", strconv.Itoa(m))
	//	} else {
	//		minute = strconv.Itoa(m)
	//	}
	//	if s <= 9 {
	//		second = utils.Join("0", strconv.Itoa(s))
	//	} else {
	//		second = strconv.Itoa(s)
	//	}
	//	//log.Println(hour,minute,second)
	//	beginTime = utils.Join(hour, ":", minute, ":", second)
	//} else {
	//	beginTime = "00:00:00"
	//}

	// 剩余使用时长 总时长-已使用时长

	//log.Println("beginTime", beginTime)
	return beginTime, useTime
}
